package com.lj.map.syn;

import com.lj.map.syn.base.HashMapKey;
import com.lj.map.syn.base.ThreadBean;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 测试是否线程安全
 *
 * 实现原理：
 * 1：synchronized: put等写操作中，且以当前首结点为锁对象 1027(1018取第一个桶）
 * 2：unsafe：读操作 934--tabAt（754）
 * Created by yangsp1 on 16/3/31.
 */
public class ConcurrentHashMapTest {
    public static void main(String args[]) {
        //线程非安全
        Map hashMap = new ConcurrentHashMap();
        Long sleepTime = 1000L;
        Thread t1 = new ThreadBean(hashMap, "t1",sleepTime);
        Thread t2 = new ThreadBean(hashMap, "t2",sleepTime);
        Thread t3 = new ThreadBean(hashMap, "t3",sleepTime);
        t1.start();
        t2.start();
        t3.start();

        //等待所有线程执行结束
        while (true) {
            if (HashMapKey.threadExcedCnt.intValue() == 3) {
                break;
            }
        }
        //排序
        List keys = new ArrayList(hashMap.keySet());
        Collections.sort(keys);

        //打印key
        for (Object o : keys) {
            System.out.println(o);
        }
    }
}
